package com.wanglixia.mobile;

import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 功能描述:
 * <p>
 * Created by Mr.wang on 2017/9/17 13:06.
 */
@WebServlet("/callBack")
public class CallBackServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = req.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + AuthUtil.APPID +
                "&secret=" + AuthUtil.APPSECRET +
                "&code=" + code +
                "&grant_type=authorization_code";
        JSONObject jsonObject = AuthUtil.doGetJson(url);
        System.out.println(jsonObject.toString());
        String openid = jsonObject.getString("openid");
        String token = jsonObject.getString("access_token");
//        String expires_in = jsonObject.getString("expires_in");
//        String refresh_token = jsonObject.getString("refresh_token");
//        String scope = jsonObject.getString("scope");
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=" + token +
                "&openid=" + openid +
                "&lang=zh_CN";
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
        System.out.println(userInfo);

        //1、使用微信用户信息直接登录，无需注册和绑定
//        req.setAttribute("info", userInfo);
//        req.getRequestDispatcher("/index1.jsp").forward(req, resp);


    }
}
